package com.cqjtu.graduation.controller;

import com.cqjtu.graduation.entity.RoleDO;
import com.cqjtu.graduation.entity.UserDO;
import com.cqjtu.graduation.service.RoleDOService;
import com.cqjtu.graduation.service.UserDOService;
import com.cqjtu.graduation.util.FileServerCommon;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.HEAD;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * springmvc的控制器
 * @author yhl
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserDOService userDOService;
    @Autowired
    private RoleDOService roleDOService;

    /**
     * 进入登录界面的方法
     * @return 视图名称
     */
    @RequestMapping("/login")
    public String login(){
        return "OrderSys/pages/login";
    }

    /**
     * 登录的方法
     * @param session session中保存状态值，0代表登录成功,并且将用户信息保存在当中，1代表用户名错误，2代表密码错误
     * @param userDO 用户信息
     * @return
     */
    @RequestMapping("/dologin")
    public String doLogin(HttpSession session, UserDO userDO){
        UserDO result=userDOService.login(userDO);
        System.out.println(result);
        if(result == null){
            UserDO temp = new UserDO();
            temp.setUserId(userDO.getUserId());
            result = userDOService.login(temp);
            if(result == null){
                session.setAttribute("loginflag",1);//用户名错误
                return "OrderSys/pages/login";
            }
            session.setAttribute("loginflag",2);//密码错误
            return "OrderSys/pages/login";
        }
        session.setAttribute("usermessage",result);
        session.setAttribute("loginflag",0);//登录成功
        if(result.getRoleDO().getRoleId() == 1){
            return "OrderSys/pages/AdminIndex";
        }
        else if(result.getRoleDO().getRoleId() == 2){
            return "OrderSys/pages/WaiterIndex";
        }
        return "OrderSys/pages/CookIndex";
    }

    /**
     * 进入注册界面方法
     * @param session
     * @return
     */
    @RequestMapping("/register")
    public String register(HttpSession session , RoleDO roleDO){
        List<RoleDO> result = roleDOService.getAllRole(roleDO);
        session.setAttribute("roles" , result);
        return "OrderSys/users/AddUser";
    }

    /**
     * 根据前台传来的数据，进行用户注册
     * @param userDO
     * @param session
     * @return
     */
    @RequestMapping("/doregister")
    public String doRegister(UserDO userDO,HttpServletRequest request,HttpSession session,@RequestParam(required = false) MultipartFile file){
        UserDO temp = new UserDO();
        temp.setUserId(userDO.getUserId());
        UserDO result = userDOService.findUserById(temp);
        if(result == null){
            userDOService.register(userDO , file);
            session.setAttribute("registerflag",0);
            return login();
        }
        session.setAttribute("registerflag",1);
        return register(session,new RoleDO());
    }

    /**
     * 分页列出所有用户，并根据条件查询
     * @param request
     * @return
     */
    @RequestMapping("/browseuser")
    public String browseUser(HttpServletRequest request, UserDO userDO){
        init(request);
        if(userDO == null){
            userDO = new UserDO();
        }
        if(userDO.getRoleDO() == null){
            userDO.setRoleDO(new RoleDO());
        }
        String userId = userDO.getUserId();
        Integer roleId = userDO.getRoleDO().getRoleId();
        request.setAttribute("userId",userId);
        request.setAttribute("roleId",roleId);
        userDO.setStart(getStart());
        userDO.setLength(PAGE_NUM);
        List<UserDO> users = userDOService.listUserDOByCondition(userDO);
        Long total = userDOService.countUserDOByCondition(userDO);
        request.setAttribute("users",users);
        request.setAttribute("total",total);
        List<RoleDO> roles = roleDOService.getAllRole(new RoleDO());
        request.setAttribute("roles",roles);
        return "OrderSys/users/BrowseUser";
    }
    /**
     *更新用户信息
     * @return 返回主页，并显示最新用户信息
     */
    @RequestMapping("/update")
    public String update(HttpSession session , UserDO userDO){
        UserDO newUserDO = userDOService.findUserById(userDO);
        List<RoleDO> result = roleDOService.getAllRole(new RoleDO());
        session.setAttribute("roles" , result);
        session.setAttribute("updateUser",newUserDO);
        return "OrderSys/users/UserMesUpdate";
    }
    @RequestMapping("/doupdate")
    public String doUpdateUserDO(HttpServletRequest request , UserDO userDO ,@RequestParam(required = false) MultipartFile file){
        System.out.println("a"+userDO);
        userDOService.updateUserDO(userDO , file);
        System.out.println("aa"+userDO);
        return browseUser(request ,new UserDO());
    }

    /**
     * 获取最新用户信息
     * @param session
     * @return
     */
    @RequestMapping("index")
    public String index(HttpSession session){
        UserDO condition = new UserDO();
        UserDO result = (UserDO) session.getAttribute("usermessage");
        condition.setUserId(result.getUserId());
        UserDO newMessage = userDOService.findUserById(condition);
        session.setAttribute("usermessage",newMessage);
        return "OrderSys/pages/index";
    }
    /**
     * 删除指定用户信息
     * @param userDO
     * @return
     */
    @RequestMapping("/delete")
    public String deleteUserDO(HttpServletRequest request,UserDO userDO){
        userDOService.deleteUserDO(userDO);
        return browseUser(request,new UserDO());
    }
    @RequestMapping("/upload")
    public String upload(@RequestParam(required = false) MultipartFile file){
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format = df.format(new Date());
        format = format + new Random().nextLong();
        String url = FileServerCommon.FILE_SERVER_HOST + format + ".jpg";//要将图片保存到网络上的完整地址
        String partUrl = format + ".jpg";// 部分地址  /xxx.jpg
        //创建Jersey框架的客户端
        Client client = new Client();
        WebResource resource = client.resource(url);
        try {
            byte[] buf;
            buf = file.getBytes();
            resource.put(String.class,buf);//通过put方式向网络url发送资源
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index";
    }
}
